import React, {useEffect, useRef, useState} from 'react';
import store from "../store";
import {changeNum} from "../store/slice/cart";

function Cart(props) {
    const [cartList,setCartList] = useState(store.getState().cart.cartList)
    useEffect(()=>{
        const unSubscribe = store.subscribe(()=>{
            setCartList(store.getState().cart.cartList)
        })
        return ()=>{
            unSubscribe()
        }
    },[])
    return (
        <div>
            {
                !cartList.length? <h3>购物车为空！</h3>:
                    cartList.map(item=>(
                        <div key={item.id}>
                            <h3>商品名称：{item.goodsName}</h3>
                            <h3>商品价格：￥{item.goodsPrice}</h3>
                            <h3>商品数目：<button onClick={()=>{
                                store.dispatch(changeNum({id:item.id,num:-1}))
                            }}>-</button>
                                <input type="text" value={item.buyNum} onChange={(e)=>{
                                    store.dispatch(changeNum({id:item.id,num:e.target.value/1}))
                                }}/>
                                <button onClick={()=>{
                                store.dispatch(changeNum({id:item.id,num:1}))
                            }}>+</button></h3>
                            <h3>小计：{(item.goodsPrice*item.buyNum).toFixed(2)}</h3>
                            <hr/>
                        </div>
                    ))
            }
        </div>
    );
}

export default Cart;